Popular Searches
Popular Course Categories
Popular Courses

Closing and Quitting Browser

Closing and Quitting Browser

WebDriver Fundamentals

Closing and Quitting Browser in Selenium

Closing and quitting the browser is an important part of Selenium WebDriver automation. After a test case or automation workflow is completed, the browser session should be properly terminated so that browser windows, tabs, WebDriver sessions, driver processes, and other resources are released.

Selenium WebDriver provides two commonly used methods for closing browser windows: close() and quit(). Although both methods are used to terminate browser activity, they have different purposes and scopes.

According to the Selenium WebDriver documentation, close() closes the current browser window, while quit() terminates the WebDriver session and closes every window associated with that session. Selenium recommends using quit() when the complete browser session has finished.


1. Selenium Training at JustAcademy

Learn Selenium Automation Testing with Java, WebDriver, TestNG, framework development, cross-browser testing, data-driven testing, Page Object Model, and real-time automation projects.

JustAcademy Selenium Automation Testing Course

Register for Selenium Course Demo


2. What Does Closing the Browser Mean in Selenium?

Closing the browser means terminating the browser window or tab that Selenium is currently controlling. Selenium WebDriver provides the close() method for this purpose.

The close() method operates on the currently selected browser window. If multiple tabs or windows are open, Selenium closes the window represented by the current window handle.

driver.close();

The important point is that close() is window-specific. It does not necessarily terminate the entire WebDriver session.


3. What Does Quitting the Browser Mean in Selenium?

Quitting the browser means completely terminating the WebDriver session. The quit() method closes all browser windows and tabs associated with the current WebDriver session and ends the session.

driver.quit();

Selenium's documentation describes quit() as the command that terminates the WebDriver session and closes every associated window.


4. Difference Between close() and quit()

Feature close() quit()
Purpose Closes the current browser window or tab Terminates the complete WebDriver session
Multiple Windows Closes only the currently selected window Closes all windows associated with the session
WebDriver Session Normally remains available Session is terminated
Driver Process May continue running Associated browser/driver resources are released
Typical Usage When working with multiple tabs/windows At the end of a complete test or test suite
Recommended for Teardown No Yes


5. Understanding close() Method

The close() method closes the current browser window or tab controlled by Selenium.

driver.close();

For example, suppose Selenium has opened three browser windows:

Window 1

Window 2

Window 3

If Selenium is currently switched to Window 2 and the following command is executed:

driver.close();

Window 2 will be closed. The other windows remain open.


6. Example of close()

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class CloseExample {

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://www.google.com");

 

        driver.close();

    }

}

In this example, Selenium opens Google and then closes the currently active browser window.


7. Understanding quit() Method

The quit() method completely terminates the current WebDriver session.

driver.quit();

When a test has finished and there is no need to continue using the browser session, quit() is normally the appropriate method.

Selenium documents that quitting a session closes all windows and tabs associated with the WebDriver session and also terminates the browser session and associated driver resources.


8. Example of quit()

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class QuitExample {

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://www.google.com");

 

        driver.quit();

    }

}

Here, the complete Selenium browser session is terminated after the test operation is completed.


9. close() with Multiple Browser Windows

Multiple-window automation is a common Selenium scenario. For example, a test may open an original page and then open another page in a new tab.

WebDriver driver = new ChromeDriver();

 

driver.get("https://www.google.com");

 

String parentWindow = driver.getWindowHandle();

 

driver.switchTo().newWindow(WindowType.TAB);

driver.get("https://www.selenium.dev");

 

driver.close();

 

driver.switchTo().window(parentWindow);

 

driver.quit();

In this example, close() closes the currently selected tab. The test then switches back to the parent window and finally uses quit() to terminate the complete session.


10. close() After Opening a New Tab

When a new tab is opened, Selenium can switch to that tab and close it when the work is completed.

String parentWindow = driver.getWindowHandle();

 

driver.switchTo().newWindow(WindowType.TAB);

driver.get("https://www.selenium.dev");

 

driver.close();

 

driver.switchTo().window(parentWindow);

This pattern is useful when the test needs to close a temporary tab while continuing the main test in the original tab.


11. quit() After Multiple Tabs

If the entire automation task is complete, there is usually no reason to close tabs individually. The complete WebDriver session can be terminated with quit().

driver.quit();

This closes all browser windows and tabs associated with that Selenium session.


12. close() vs quit() Practical Example

WebDriver driver = new ChromeDriver();

 

driver.get("https://www.google.com");

 

driver.switchTo().newWindow(WindowType.TAB);

driver.get("https://www.selenium.dev");

 

// Close only the current tab

driver.close();

 

// Close the complete Selenium session

driver.quit();

The first command closes only the active tab. The second command terminates the complete browser session.


13. What Happens If You Use close() Instead of quit()?

Using close() when the intention is to finish the entire test session can leave the WebDriver session or related resources active, particularly in more complex multi-window or test-suite scenarios.

This can result in:

  • Remaining browser windows or tabs.
  • Background driver processes.
  • Unused WebDriver sessions.
  • Resource consumption.
  • Problems in subsequent tests.
  • Difficulty managing multiple browser sessions.

Selenium specifically recommends using quit() to end a complete session.


14. What Happens If You Use quit()?

When quit() is called, Selenium ends the WebDriver session.

The general flow is:

Test Execution

      ↓

Browser Session

      ↓

Test Completed

      ↓

driver.quit()

      ↓

Close Browser Windows

      ↓

Terminate WebDriver Session

      ↓

Release Resources

After calling quit(), the WebDriver object should not be used for further browser commands.


15. Using quit() in TestNG

In TestNG-based Selenium frameworks, quit() is commonly placed inside a teardown method so that the browser session is closed after the test.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

public class LoginTest {

 

    WebDriver driver;

 

    @BeforeMethod

    public void setup() {

        driver = new ChromeDriver();

        driver.manage().window().maximize();

    }

 

    @Test

    public void loginTest() {

        driver.get("https://example.com/login");

        System.out.println("Login test executed");

    }

 

    @AfterMethod

    public void tearDown() {

        if (driver != null) {

            driver.quit();

        }

    }

}

The teardown method ensures that the browser session is properly terminated after the test.


16. Why Use if(driver != null)?

Checking whether the driver is null before calling quit() makes teardown code safer.

if (driver != null) {

    driver.quit();

}

This prevents a teardown method from attempting to call quit() on a driver object that was never initialized.


17. Selenium with JUnit Teardown

JUnit also provides lifecycle annotations that can be used for browser cleanup.

import org.junit.jupiter.api.AfterEach;

import org.junit.jupiter.api.BeforeEach;

import org.junit.jupiter.api.Test;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class LoginTest {

 

    WebDriver driver;

 

    @BeforeEach

    public void setup() {

        driver = new ChromeDriver();

    }

 

    @Test

    public void testLogin() {

        driver.get("https://example.com/login");

    }

 

    @AfterEach

    public void tearDown() {

        if (driver != null) {

            driver.quit();

        }

    }

}

Selenium's own examples demonstrate using teardown lifecycle methods to call driver.quit() after tests.


18. Closing Browser in Python Selenium

Python Selenium uses the same basic concepts.

close()

from selenium import webdriver

 

driver = webdriver.Chrome()

 

driver.get("https://www.google.com")

 

driver.close()

quit()

from selenium import webdriver

 

driver = webdriver.Chrome()

 

driver.get("https://www.google.com")

 

driver.quit()

The Python WebDriver API follows the same distinction between closing a current window and terminating the browser session.


19. Python Selenium Teardown Example

from selenium import webdriver

 

def test_google():

    driver = webdriver.Chrome()

 

    try:

        driver.get("https://www.google.com")

        print(driver.title)

    finally:

        driver.quit()

 

test_google()

The finally block is useful when cleanup should happen even if an exception occurs during test execution.


20. JavaScript Selenium quit()

Selenium WebDriver also supports browser session termination in JavaScript.

const { Builder } = require("selenium-webdriver");

 

(async function example() {

 

    let driver = await new Builder()

        .forBrowser("chrome")

        .build();

 

    try {

        await driver.get("https://www.google.com");

        console.log(await driver.getTitle());

    } finally {

        await driver.quit();

    }

 

})();

The Selenium JavaScript API documents quit() as terminating the browser session and invalidating the WebDriver instance for further commands.


21. Using try-finally for Browser Cleanup

A robust automation script should ensure that browser resources are released even when an unexpected error occurs.

WebDriver driver = new ChromeDriver();

 

try {

    driver.get("https://example.com");

 

    // Test steps

    System.out.println(driver.getTitle());

 

} finally {

    driver.quit();

}

The finally block executes after the try block, including when an exception interrupts normal execution.


22. Browser Cleanup After an Exception

Consider a test where an exception occurs during an assertion or element interaction.

WebDriver driver = new ChromeDriver();

 

try {

    driver.get("https://example.com");

 

    // Test operation

    driver.findElement(By.id("invalidElement")).click();

 

} finally {

    driver.quit();

}

Even if the element is not found and an exception occurs, the cleanup code attempts to terminate the WebDriver session.


23. Browser Cleanup in Automation Frameworks

In professional Selenium frameworks, browser startup and browser termination are generally centralized in setup and teardown methods.

Test Start

    ↓

Create WebDriver

    ↓

Open Browser

    ↓

Execute Test

    ↓

Capture Result

    ↓

Quit WebDriver

    ↓

Test End

This structure avoids repeating browser cleanup logic in every individual test method.


24. close() and Window Handles

When working with multiple windows, Selenium provides window handles to identify browser windows.

String parent = driver.getWindowHandle();

 

Set windows = driver.getWindowHandles();

 

for (String window : windows) {

    if (!window.equals(parent)) {

        driver.switchTo().window(window);

        driver.close();

    }

}

 

driver.switchTo().window(parent);

driver.quit();

This approach can be useful when a test needs to close selected child windows while keeping the main browser window available.


25. Closing All Child Windows

A common automation requirement is to close child windows while keeping the parent window open.

String parent = driver.getWindowHandle();

 

for (String windowHandle : driver.getWindowHandles()) {

 

    if (!windowHandle.equals(parent)) {

        driver.switchTo().window(windowHandle);

        driver.close();

    }

}

 

driver.switchTo().window(parent);

After the required work is completed, the parent browser can also be terminated:

driver.quit();


26. close() on the Last Browser Window

Selenium's WebDriver API specifies that close() closes the current window and may quit the browser when that window is the last one open.

Because of this behavior, test frameworks should not rely on close() as a replacement for an explicit complete-session cleanup strategy.


27. Why quit() Is Preferred for Test Teardown

For complete test cleanup, quit() provides a clear and explicit instruction to terminate the WebDriver session.

  • It closes all windows and tabs associated with the session.
  • It terminates the browser session.
  • It releases WebDriver-related resources.
  • It helps prevent leftover browser processes.
  • It makes test teardown predictable.
  • It is suitable for framework-level cleanup.

Selenium recommends calling quit() when the browser session is finished.


28. Common Mistake: Using close() Everywhere

One common mistake is writing:

@AfterMethod

public void tearDown() {

    driver.close();

}

For a complete test-session teardown, quit() is generally more appropriate:

@AfterMethod

public void tearDown() {

    if (driver != null) {

        driver.quit();

    }

}


29. Common Mistake: Calling quit() Too Early

Another mistake is terminating the driver before all required test steps have finished.

driver.get("https://example.com");

 

driver.quit();

 

driver.findElement(By.id("username")).sendKeys("admin");

The final command cannot be performed because the WebDriver session has already been terminated.

The correct order is:

Open Browser

     ↓

Perform Test

     ↓

Validate Result

     ↓

Capture Required Data

     ↓

Quit Browser


30. Common Mistake: Calling Commands After quit()

driver.quit();

 

driver.get("https://example.com");

Once the WebDriver session has been terminated, the same driver instance should not be used for additional browser operations. The JavaScript Selenium documentation explicitly states that after quit(), the WebDriver instance is invalidated for further browser commands.


31. Browser Closing in Page Object Model

In a Page Object Model framework, browser lifecycle management should generally remain in the test or framework setup/teardown layer rather than inside individual page classes.

public class BaseTest {

 

    protected WebDriver driver;

 

    public void setup() {

        driver = new ChromeDriver();

    }

 

    public void tearDown() {

        if (driver != null) {

            driver.quit();

        }

    }

}

Individual page objects can then focus on page elements and actions while the base test manages the browser lifecycle.


32. Browser Cleanup in a Base Test Class

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

 

public class BaseTest {

 

    protected WebDriver driver;

 

    @BeforeMethod

    public void setUp() {

        driver = new ChromeDriver();

        driver.manage().window().maximize();

    }

 

    @AfterMethod

    public void tearDown() {

        if (driver != null) {

            driver.quit();

        }

    }

}

This structure allows multiple test classes to reuse the same browser setup and cleanup mechanism.


33. Browser Cleanup in Parallel Testing

Parallel execution makes proper browser lifecycle management even more important. Each test should have its own appropriate WebDriver instance or isolated driver management strategy.

Test 1 → WebDriver 1 → Browser 1 → quit()

 

Test 2 → WebDriver 2 → Browser 2 → quit()

 

Test 3 → WebDriver 3 → Browser 3 → quit()

Incorrect driver sharing can cause one test to close or quit a browser session that another test is still using.


34. Browser Cleanup with Selenium Grid

When Selenium Grid or remote WebDriver is used, proper session termination becomes especially important because the remote browser resources are being used on another environment.

Remote Test

     ↓

Create Remote WebDriver

     ↓

Execute Test

     ↓

Validate Result

     ↓

driver.quit()

     ↓

Release Remote Session

Selenium's documentation notes that quitting a session also notifies Selenium Grid that the browser is no longer in use when Grid is involved.


35. Browser Cleanup and Resource Management

Browser automation consumes system resources such as memory, CPU, browser processes, driver processes, ports, and remote execution slots.

Failing to terminate sessions properly can contribute to resource consumption during large automation suites.

Test Case 1

   ↓

Browser Session

   ↓

quit()

   ↓

Resources Released

 

Test Case 2

   ↓

Browser Session

   ↓

quit()

   ↓

Resources Released


36. Recommended Test Teardown Pattern

A simple and reusable Selenium teardown pattern is:

@AfterMethod

public void tearDown() {

    if (driver != null) {

        driver.quit();

    }

}

This is especially useful for TestNG test suites where every test method should clean up its browser session after execution.


37. Complete Selenium Browser Lifecycle

Initialize WebDriver

        ↓

Launch Browser

        ↓

Navigate to Application

        ↓

Perform Test Actions

        ↓

Validate Expected Results

        ↓

Capture Logs / Screenshots if Required

        ↓

Complete Test

        ↓

driver.quit()

        ↓

Terminate Browser Session

        ↓

Release Resources


38. Practical Example: Complete Browser Lifecycle

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class BrowserLifecycleTest {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

 

            driver.manage().window().maximize();

 

            driver.get("https://example.com");

 

            String title = driver.getTitle();

 

            System.out.println("Page Title: " + title);

 

            // Test steps

            System.out.println("Test execution completed");

 

        } finally {

 

            driver.quit();

        }

    }

}

This example demonstrates a clean browser lifecycle where the browser is started, the test is executed, and the WebDriver session is terminated in the cleanup phase.


39. close() and quit() Quick Comparison

Scenario Recommended Method
Close the current tab close()
Close a child window close()
Finish complete test quit()
Finish test suite browser session quit()
Terminate all browser windows quit()
Clean up TestNG session quit()
Clean up JUnit session quit()
Close selected temporary tab close()


40. Best Practices for Closing and Quitting Browser

  • Use quit() when the complete WebDriver session has finished.
  • Use close() when you specifically need to close the current window or tab.
  • Place quit() in TestNG or JUnit teardown methods.
  • Use if(driver != null) before cleanup when appropriate.
  • Use try-finally when browser cleanup must happen even after an exception.
  • Do not execute browser commands after calling quit().
  • Use window handles carefully when closing individual tabs.
  • Keep browser lifecycle management centralized in the automation framework.
  • Ensure each parallel test has an appropriately isolated WebDriver session.
  • Always clean up remote WebDriver sessions after execution.


41. Common Interview Questions

Q1. What is the difference between close() and quit() in Selenium?

Answer: close() closes the current browser window or tab, whereas quit() terminates the complete WebDriver session and closes all associated windows.

Q2. Which method should generally be used at the end of a Selenium test?

Answer: driver.quit() is generally used to terminate the complete browser session and release associated resources.

Q3. Can close() be used with multiple browser windows?

Answer: Yes. Selenium closes the currently selected browser window. The test can switch between windows using window handles and close selected windows.

Q4. What happens after quit()?

Answer: The WebDriver session is terminated and all associated browser windows are closed. The driver should not be used for further browser commands.

Q5. Where should quit() be placed in TestNG?

Answer: It is commonly placed inside a teardown method such as @AfterMethod or another appropriate lifecycle method.

Q6. Why is browser cleanup important?

Answer: Proper cleanup prevents leftover browser and driver processes, releases resources, and helps maintain reliable execution of subsequent tests.

Q7. Can close() terminate the complete browser session?

Answer: The WebDriver specification/API defines close() as closing the current window and indicates that the browser is quit when that is the last open window. For explicit complete-session cleanup, quit() should be used.


42. Quick Revision

Concept Meaning
close() Closes the current browser window or tab.
quit() Terminates the complete WebDriver session.
Window Handle Unique identifier used to work with browser windows.
Teardown Cleanup phase executed after test execution.
try-finally Useful for ensuring browser cleanup after errors.
TestNG @AfterMethod Common location for test-level browser cleanup.


43. Complete Browser Closing Flow

Start Test

    ↓

Create WebDriver

    ↓

Open Browser

    ↓

Navigate to Application

    ↓

Perform Test Actions

    ↓

Validate Results

    ↓

Are More Tabs Required?

    ↓

Yes → Switch Window → close() → Continue

    ↓

No

    ↓

Test Completed

    ↓

quit()

    ↓

Close All Associated Windows

    ↓

Terminate WebDriver Session

    ↓

Release Resources

    ↓

End Test


44. Practical Project: Browser Lifecycle Test

In a practical Selenium automation project, browser lifecycle management can be implemented as a reusable base framework.

public class BrowserManager {

 

    private WebDriver driver;

 

    public void startBrowser() {

        driver = new ChromeDriver();

        driver.manage().window().maximize();

    }

 

    public WebDriver getDriver() {

        return driver;

    }

 

    public void closeBrowser() {

        if (driver != null) {

            driver.quit();

        }

    }

}

A test can then use the manager:

public class LoginTest {

 

    public static void main(String[] args) {

 

        BrowserManager browser = new BrowserManager();

 

        browser.startBrowser();

 

        try {

 

            WebDriver driver = browser.getDriver();

 

            driver.get("https://example.com/login");

 

            System.out.println(driver.getTitle());

 

        } finally {

 

            browser.closeBrowser();

        }

    }

}

This approach separates browser lifecycle management from individual test logic.


45. Learning Outcomes

After completing this topic, you should be able to:

  • Understand browser lifecycle management in Selenium.
  • Understand the difference between close() and quit().
  • Close individual tabs and windows using close().
  • Terminate complete WebDriver sessions using quit().
  • Work with multiple browser windows and window handles.
  • Implement browser cleanup in TestNG.
  • Implement browser cleanup in JUnit.
  • Use try-finally for reliable resource cleanup.
  • Manage browser sessions in Page Object Model frameworks.
  • Understand browser cleanup during parallel execution.
  • Understand the importance of terminating remote Selenium sessions.
  • Apply professional browser teardown practices in Selenium projects.


46. Recommended Selenium Training Resource

For structured learning of Selenium WebDriver, Java, TestNG, Page Object Model, automation frameworks, cross-browser testing, data-driven testing, and real-time automation projects, explore the Selenium Automation Testing course at JustAcademy.

JustAcademy Selenium Automation Testing Course

You can also register for a course demo to understand the training structure and learning approach.

Register for Selenium Course Demo


47. Final Summary

Closing and quitting the browser are essential parts of Selenium WebDriver session management. The close() method is primarily used to close the currently selected browser window or tab, making it useful when a test works with multiple windows or temporary tabs.

The quit() method is used to terminate the complete WebDriver session and close all browser windows associated with that session. Selenium recommends using quit() when the browser session is finished.

In professional automation frameworks, browser cleanup should be implemented systematically through TestNG or JUnit teardown methods, base test classes, or finally blocks. Proper cleanup helps prevent unnecessary browser and driver processes and supports reliable execution of subsequent tests.

The key rule to remember is:

close() → Close Current Window / Tab

 

quit() → Terminate Complete WebDriver Session

Understanding the correct use of close() and quit() is an essential Selenium WebDriver skill for writing stable, maintainable, and professional automation test scripts.

whatsapp